using Coffee.DataModels;

namespace Coffee.DataMappers
{
    /// <summary>
    /// A generic type for data mapper that implements a few common background methods
    /// so we don't have to implement them in the actual mappers.
    /// Requires a new() constraint just so we can call new T()
    /// </summary>
    public abstract class SurveyQuestionTableMapper<T> : IDataMapper where T : DataModel, new()
    {
        protected T currentAnswer;
        protected T previousAnswer;


        public T Current { get { return currentAnswer; } }
        public T Previous { get { return previousAnswer; } }


        public SurveyQuestionTableMapper()
        {
            Initialize();
        }

        protected virtual void Initialize()
        {
            currentAnswer = new T();
            previousAnswer = new T();
        }

        public new virtual void Load() { }
        public new virtual void Update() { }

        void IDataMapper.Load()
        {
            Load();
        }

        DataModel IDataMapper.Current
        {
            get { return Current; }
        }

        DataModel IDataMapper.Previous
        {
            get { return Previous; }
        }

        void IDataMapper.Update()
        {
            Update();
        }

        public bool? ReadBool(object value)
        {
            if (value == System.DBNull.Value)
            {
                return null;
            }
            else
            {
                return (bool?)value;
            }
        }

        public int? ReadInt(object value)
        {
            if (value == System.DBNull.Value)
            {
                return null;
            }
            else
            {
                return (int?)value;
            }
        }

        public Q ReadNullable<Q>(object value)
        {
            if (value == System.DBNull.Value)
            {
                return default(Q);
            }
            else
            {
                return (Q)value;
            }
        }

        public string ReadString(object value)
        {
            if (value == System.DBNull.Value)
            {
                return null;
            }
            else
            {
                return (string)value;
            }
        }
    }
}